package com.wfw.controller;

import com.google.common.collect.Lists;
import com.wfw.dto.OrderMasterDto;
import com.wfw.enums.ResultEnum;
import com.wfw.exception.SellException;
import com.wfw.model.OrderDetail;
import com.wfw.model.ProductInfo;
import com.wfw.service.OrderService;
import com.wfw.service.ProductInfoService;
import com.wfw.service.RedisLockService;
import com.wfw.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private ProductInfoService productInfoService;

//    @Autowired
//    private RedisLockService redisLockService;

    private Integer count=0;

    private static final long TIMEOUT=10*1000;

    @GetMapping("create")
    public ResultVo create(){
//        long timeoutTime=System.currentTimeMillis()+TIMEOUT;
//        if (!redisLockService.lock("productId",String.valueOf(timeoutTime))){
//            throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
//        }

        OrderMasterDto orderMasterDto=new OrderMasterDto();
        orderMasterDto.setBuyerName("李四");
        orderMasterDto.setBuyerPhone("13666136666");
        orderMasterDto.setBuyerAddress("J2");
        orderMasterDto.setBuyerOpenid("111111");

        List<OrderDetail> orderDetailList= Lists.newArrayList();

        OrderDetail orderDetail1=new OrderDetail();
        orderDetail1.setProductId("2");
        orderDetail1.setProductQuantity(1);
//
//        OrderDetail orderDetail2=new OrderDetail();
//        orderDetail2.setProductId("103");
//        orderDetail2.setProductQuantity(1);
//
//        OrderDetail orderDetail3=new OrderDetail();
//        orderDetail3.setProductId("1101");
//        orderDetail3.setProductQuantity(1);

        orderDetailList.add(orderDetail1);
//        orderDetailList.add(orderDetail2);
//        orderDetailList.add(orderDetail3);

        orderMasterDto.setOrderDetailList(orderDetailList);

        orderService.create(orderMasterDto);
        count++;

        ProductInfo productInfo=productInfoService.findOne("2");

        int rest=productInfo.getProductStock();
//        redisLockService.unLock("productId",String.valueOf(timeoutTime));


        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return ResultVo.createBySuccessData("购买人数："+count+",剩余库存："+rest+",和为："+(count+rest));
    }

}
